package com.shareit.ocr.domain.simulator;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.NoSuchFrameException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.shareit.ocr.domain.Dama2Web;
import com.shareit.ocr.domain.Dama2Web.DecodeResult;
import com.shareit.ocr.domain.template.InvoiceDataTemplate;
import com.shareit.ocr.enums.ResultEnum;
import com.shareit.ocr.exception.SimulatorException;
import com.shareit.ocr.util.PicUtil;

public class WebSimulator extends BaseSimulator {
	
	private final Logger logger = LoggerFactory.getLogger(WebSimulator.class);
		
	
	//浏览器模拟器
	private  HtmlUnitDriver webdriver;
	

	public WebSimulator() {
		super();
		//创建浏览器模拟器
		webdriver = new HtmlUnitDriver(BrowserVersion.INTERNET_EXPLORER,true);
		webdriver.setJavascriptEnabled(true);
		System.out.println("BrowserVersion:" + webdriver.getBrowserVersion().toString());
		//设置浏览器模拟器等待渲染时间
		webdriver.manage().timeouts().implicitlyWait(2,TimeUnit.SECONDS);	
	}
	
	@Override
	public void close() {
		webdriver.quit();
	}
	
	private boolean isCorrectCode(String codeinfo) {
		
		return codeinfo.contains("红色") || codeinfo.contains("蓝色") || codeinfo.contains("黄色");
//		return codeinfo.contains("黄色");
	}
	
	@Override
	public void getYzmCode(InvoiceDataTemplate idt){
	
		infoLog("开始获取验证码");
		
		WebElement web_fpdm;
		WebElement web_fphm;
		WebElement web_kprq;
		WebElement web_kjje;
		WebElement web_yzmimg = null;
		WebElement web_yzmimg_info = null;
		
		String img_src_attr="";
		String imgInfo ="";

		
		webdriver.get(this.simulatorProperties.getStartURL());
		imgInfo ="";
		img_src_attr ="";

		web_fpdm = webdriver.findElement(By.id("fpdm"));
		web_fpdm.sendKeys(idt.getHeader().getFieldValue("fpdm"));
		
		web_fphm = webdriver.findElement(By.id("fphm"));
		web_fphm.sendKeys(idt.getHeader().getFieldValue("fphm"));
		
		web_kprq = webdriver.findElement(By.id("kprq"));
		web_kprq.sendKeys(idt.getHeader().getFieldValue("kprq"));
		
		if(webdriver.findElement(By.id("fpdmjy")).getText().contains("有误")) {
			throw new SimulatorException(ResultEnum.INVOICE_FPDM_ERROR);
		}
		
		if(webdriver.findElement(By.id("fphmjy")).getText().contains("有误")) {
			throw new SimulatorException(ResultEnum.INVOICE_FPHM_ERROR);
		}
		if(webdriver.findElement(By.id("kprqjy")).getText().contains("有误")) {
			throw new SimulatorException(ResultEnum.INVOICE_FPRQ_ERROR);
		}
		
		web_kjje = webdriver.findElement(By.id("kjje"));
		web_kjje.sendKeys(idt.getHeader().getExtInfo());
		
		do {
			web_yzmimg = webdriver.findElement(By.id("yzm_img"));
			web_yzmimg.click();
			while (!img_src_attr.startsWith("data:")) {
				img_src_attr = web_yzmimg.getAttribute("src");
			}
		
			web_yzmimg_info=webdriver.findElement(By.id("yzminfo"));
			imgInfo = web_yzmimg_info.getText();
		
			if(imgInfo.contains("黄色")) {
				imgInfo = "黄色验证码";
			}else if(imgInfo.contains("蓝色")) {
				imgInfo = "蓝色验证码";
			}else if (imgInfo.contains("红色")) {
				imgInfo = "红色验证码";
			}
		}
		while(!isCorrectCode(imgInfo));
		
		DecodeResult decoderesult = null;
		Dama2Web dw = new Dama2Web(this.simulatorProperties.getDamaProperties());
		infoLog("处理验证码图片");
		byte[] data = PicUtil.getCodeData(img_src_attr, imgInfo, 30);
		infoLog("处理验证码图片完成，开始获取验证码结果");
		decoderesult = dw.d2File(200, 60, data);
		infoLog("获取到验证码结果 " + decoderesult.result);
		
		WebElement web_yzm = null;
		WebElement web_checkfp=null;
		WebElement web_popup_message = null;
		String message = "";
		
		web_yzm = webdriver.findElement(By.id("yzm"));
		web_yzm.sendKeys(decoderesult.result);
		
		
		web_checkfp = webdriver.findElement(By.id("checkfp"));
		infoLog("点击验证");

		web_checkfp.click();
		infoLog("点击验证完成");
		
		webdriver.switchTo().defaultContent();
	    try{
	    	web_popup_message =webdriver.findElement(By.id("popup_message")); 
	    	message = web_popup_message.getText();
	    	infoLog("弹出错误对话框:" + message);
	    	throw new SimulatorException(ResultEnum.VALID_ERROR);		
	    }catch(NoSuchElementException e){
	    	infoLog("未弹出错误对话框");
	    }

	    infoLog("切换到 dialog-body");
	    try {
		 webdriver.switchTo().frame("dialog-body");
	  
	    }
	    catch(NoSuchFrameException e) {
    	  message = "未找到frame dialog-body";
    	  infoLog(message);
	    }	   
	}
	
	@Override
	public void getDetailInfo(InvoiceDataTemplate idt) {
	
      if(webdriver.findElements(By.id("cyjg")).size() != 0){
    	  throw new SimulatorException(ResultEnum.VALID_ERROR);
      }
      
	  try{ 
		  
		  idt.getHeader().setDataFields(webdriver);
	      String parent_xpath = "//table[@class='fppy_table_box']/tbody/tr";
	      List<WebElement> elements = webdriver.findElements(By.xpath(parent_xpath));
	      
	      //当前tr中包含了 明细抬头和 合计行数据，需要去掉
	      if(elements.size() > 3) {
	    	  idt.getItems().setItemsData(elements.subList(1, elements.size() -2));
	      }
		   
	      
	  }catch(Exception e) {
		    e.printStackTrace();
	    	throw new SimulatorException(ResultEnum.PAGE_ERROR);
	    }
	}

	@Override
	public Logger getLogger() {
		// TODO Auto-generated method stub
		return this.logger;
	}
}
